<?php

class Materials_Model_Comment_Observer_MaterialCommentsUpdater extends Workset_Model_Observer_Abstract
{

    protected $_isStored;

    protected $_count;

    public function beforeSave(Workset_Model_Subject_Interface $object, $data = null) {
        $this->_isStored = null;

        if ($object instanceof Materials_Model_Comment) {
            $this->_isStored = $object->isStored();
        }
    }

    /**
     * Увеличивает счетчик комментариев у материала
     *
     * @param Workset_Model_Subject_Interface $material
     * @param  $data
     * @return void
     */
	public function afterSave(Workset_Model_Subject_Interface $object, $data = null) {

		if ($object instanceof Materials_Model_Comment && !$this->_isStored) {

			$material = $object->getMaterial();
            
            $material['comments'] += 1;
            $material['last_comment_id'] = $object->getId();

            $material->save();
        }

        $this->_isStored = null;
	}

    public function beforeDelete(Workset_Model_Subject_Interface $object, $data = null) {
        $this->_reset();

        if ($object instanceof Materials_Model_Comment) {
            $this->_isStored = $object->isStored();

            if ($this->_isStored) {
                $this->_count = 1 + $object->getAnswersCount();
            }
        }
    }

    /**
     * Уменьшает счетчик комментариев у материала
     *
     * @param Workset_Model_Subject_Interface $object
     * @param  $data
     * @return void
     */
    public function afterDelete(Workset_Model_Subject_Interface $object, $data = null) {

        if ($object instanceof Materials_Model_Comment && $this->_isStored) {

            $oldData = $object->getOldData();

            if ($oldData['material_id'] > 0) {
                $material = Materials_Model_Material::getInstance($oldData['material_id']);

                if ($material['comments'] >= $this->_count) {
                    $material['comments'] -= $this->_count;
                } else {
                    $material['comments'] = 0; 
                }

                //если удаленный комментарий был указан как самый последний у материала
                //заменим его на предыдущий
                if ($material['last_comment_id'] == $oldData['id']) {
                    $lastComment = Materials_Model_Comment::getLastComment(array(
                        'material_id = ?' => $material->getId()
                    ));

                    if ($lastComment) {
                        $material['last_comment_id'] = $lastComment->getId();
                    } else {
                        $material['last_comment_id'] = null;
                    }
                }

                $material->save();
            }
        }

        $this->_reset();
    }

    protected function _reset() {
        $this->_isStored = null;
        $this->_count = null;
    }


}